package org.ipmsg.core;

import org.ipmsg.core.event.MemberListEvent;
import org.ipmsg.core.event.MemberListListener;
import java.util.Enumeration;
import java.util.Hashtable;

public class MemberList {

    private Hashtable listeners;
    private Hashtable members;

    public MemberList() {
        listeners = new Hashtable();
        members = new Hashtable();
    }

    public void addMember(Member member) {
        members.put(member.getAddress(), member);
    }

    public Member getMember(String address) {
        if (members.containsKey(address)) {
            return (Member) members.get(address);
        } else {
            return new Member();
        }
    }

    public boolean isExist(Member member) {
        return members.containsKey(member.getAddress());
    }

    public void removeMember(String address) {
        members.remove(address);
    }

    public int length() {
        return members.size();
    }

    public void removeAll() {
        members.clear();
    }

    public synchronized String[][] toArray() {
        String array[][] = new String[length()][];
        Enumeration em = members.elements();
        for (int i = 0; i < array.length; i++) {
            array[i] = ((Member) em.nextElement()).toArray();
        }

        return array;
    }

    public void addListListener(MemberListListener listener) {
        listeners.put(listener, listener);
    }

    public void removeListListener(MemberListListener listener) {
        listeners.remove(listener);
    }

    /**
     * 刷新
     * 向没一个监听器发送“用户列表事件”MemberListEvent
     */
    public void refurbish() {
        MemberListListener listener;
        for (Enumeration em = listeners.elements(); em.hasMoreElements(); listener.updateMemberList(new MemberListEvent(this, toArray()))) {
            listener = (MemberListListener) em.nextElement();
        }

    }
}
